class ProjectsController < ApplicationController
  include Concerns::ProjectV2
  before_action :set_project, except: [:index, :new, :create, :recv, :recv_v2, :access_token]
  before_action :set_rds_version, except: [:index, :new, :create]
  skip_before_action :verify_authenticity_token, only: [:recv, :recv_v2, :access_token]
  skip_before_action :authenticate_user!, only: [:recv, :recv_v2, :access_token]

  def index
    @projects = current_user.projects.all
  end

  def show
    @panel_heading = "#{@project.name} | api_v1 接口"
    @rds = rds
  end

  def set_settings
    rds.set(:url        , params["url"])
    rds.set(:appid      , params["appid"])  
    rds.set(:secret     , params["secret"])
    rds.set(:sso_secret , params["sso_secret"])
    rds.set(:openid     , params["openid"])
    rds.set(:email      , params["email"])
    rds.set(:number     , params["number"])
    @rds = rds
    redirect_to @project
  end

  def access_token
    if params[:from] != 'udesk'
      return render(json: {"error_code" => 100, "error_msg" => 'error_msg'} )
    end
    access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=#{rds.get(:appid)}&secret=#{rds.get(:secret)}"
    ret = RestClient.get access_token_url
    m_token = JSON.parse(ret)["access_token"]
    render json: {"error_code" => 0, "error_msg" => 'SUCCESS', "data" => {"token" => m_token}}.to_json
  end

  def send_msg
    content   = params["content"]
    number    = rds.get(:number)
    email     = rds.get(:email)
    timestamp = Time.now.strftime("%Y%m%d%H%M%S")
    query     = "number=#{number}&email=#{email}&timestamp=#{timestamp}"
    sign      = Digest::MD5.hexdigest(query + "&#{rds.get(:sso_secret)}").upcase

    xml = %Q(<xml>
  <FromUserName><![CDATA[#{rds.get(:openid)}]]></FromUserName>
  <Number><![CDATA[#{number}]]></Number>
  <Email><![CDATA[#{email}]]></Email>
  <Content><![CDATA[#{content}]]></Content>
  <CreateTime><![CDATA[#{timestamp}]]></CreateTime>
  <MsgType><![CDATA[text]]></MsgType>
  <MsgId><![CDATA[#{timestamp}]]></MsgId>
  </xml>)
    
    url      = rds.get(:url) + "?#{query}&sign=#{sign}"
    rsp_body = post_xml(url, xml)  
    msg = JSON.parse(rsp_body)['msg']

    raw      = rds.get(:rsp_body)  
    rsp_body = Time.now.strftime("%M:%S") + " | " + (msg || '') + "\n" + (raw || '')
    rds.set(:rsp_body, rsp_body)
    @rds     = rds  
    redirect_to @project
  end

  def cls_msg
    rds.set(:rsp_body, '')
    redirect_to @project
  end

  def cls_push
    rds.set(:push_info, '')
    redirect_to @project
  end



  # GET /projects/new
  def new
    @project = current_user.projects.new
  end

  # GET /projects/1/edit
  def edit
  end

  # POST /projects
  # POST /projects.json
  def create
    @project = current_user.projects.new(project_params)

    respond_to do |format|
      if @project.save
        format.html { redirect_to projects_url, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /projects/1
  # PATCH/PUT /projects/1.json
  def update
    respond_to do |format|
      if @project.update(project_params)
        format.html { redirect_to @project, notice: 'Project was successfully updated.' }
        format.json { render :show, status: :ok, location: @project }
      else
        format.html { render :edit }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project.destroy
    respond_to do |format|
      format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def recv
    @project = Project.find(params[:id])
    @request_payload = JSON.parse request.body.read
    Rails.logger.info "request: #{@request_payload.inspect}"
    old = rds.get :push_info
    rds.set(:push_info, "#{Time.now}|#{@request_payload.inspect}\n#{old}")
    
    render json: ""
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_project
      @project = current_user.projects.find(params[:id])
    end

    def set_rds_version
      @project ||= Project.find(params[:id])
      @v2 ||= (action_name =~ /_v2$/)
      @rds = rds
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
      params.fetch(:project, {}).permit(:name, :config)
    end

    def rds
      return @test_redis if @test_redis
      namespace = @v2 ? "v2:#{@project.id}" : "#{@project.id}"
      @test_redis = Redis::Namespace.new(namespace, :redis=> $redis)
    end
end
